﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infratructure.Interfares;
using B.S.BaseData.Read.Api.Dtos;
using B.S.BaseData.Write.Api.Application.Command;
using MediatR;

namespace B.S.BaseData.Read.Api.Application.CommandHander
{
    public class AdditiveRoleCommandHander : IRequestHandler<AdditiveRoleCommand, ApiResult<List<AdditiveRoleDto>>>
    {

        private readonly IMapper mapper;
        private readonly IBaseRequsitory<Role> roleRequsitory;
        private readonly IBaseRequsitory<Menu> menuRequsitory;
        private readonly IBaseRequsitory<RoleMenu> roleMenuRequsitory;

        public AdditiveRoleCommandHander(IMapper mapper, IBaseRequsitory<Role> roleRequsitory, IBaseRequsitory<Menu> menuRequsitory, IBaseRequsitory<RoleMenu> roleMenuRequsitory)
        {
            this.mapper = mapper;
            this.roleRequsitory = roleRequsitory;
            this.menuRequsitory = menuRequsitory;
            this.roleMenuRequsitory = roleMenuRequsitory;
        }

        /// <summary>
        /// 反添角色权限操作
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<AdditiveRoleDto>>> Handle(AdditiveRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<AdditiveRoleDto>> result = new ApiResult<List<AdditiveRoleDto>>();

            var role = roleRequsitory.GetAllAsync();
            var menu = menuRequsitory.GetAllAsync();
            var roleMenu = roleMenuRequsitory.GetAllAsync();

            var linq = from r in role
                       join rm in roleMenu on r.RoleId equals rm.RoleId
                       join m in menu on rm.MenuId equals m.Id
                       where request.RoleId == rm.RoleId
                       select new AdditiveRoleDto
                       {
                           RoleId = r.RoleId,
                           RoleName = r.RoleName,
                           Id = m.Id,
                           MenuName = m.MenuName
                       };

            result.Code = ApiEnum.显示成功;
            result.Msg = ApiEnum.显示成功.ToString();
            var entity = linq.OrderBy(x => x.RoleId).ToList();

            result.Data = mapper.Map<List<AdditiveRoleDto>>(entity);

            return Task.FromResult(result);

        }
    }
}
